<?php

namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;
use Xin\Hint\Facades\Hint;

class ValidationExceptionHandler extends ExceptionHandler
{
    /**
     * @param Throwable $throwable
     * @param ResponsePlusInterface $response
     * @return ResponsePlusInterface
     */
    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        $this->stopPropagation();
        $response = $response->withHeader('content-type', 'application/json; charset=utf-8');

        $body = $throwable->validator->errors()->first();
        return $response->setStatus($throwable->status)->setBody(new SwooleStream(
            Hint::error($body, $throwable->status)
        ));
    }

    /**
     * @param Throwable $throwable
     * @return bool
     */
    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}
